package com.imyours.webservice.services;

import org.hibernate.Session;

import com.imyours.model.department.DepartmentEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.webservice.service.Context;
import com.imyours.webservice.service.ContextService;
import com.imyours.webservice.services.annotation.Service;

/**
 * 插入新的部门方法
 * 
 * @author SLevenc
 * 
 */
@Service(name = "insertDepartment")
public class InsertDepartment extends ContextService {

	public InsertDepartment(Context context) {
		super(context);
	}

	public void execute() {
		if (isAdmin()) {
			UserEntity user = getUserEntity();
			String parentDepartmentPara = context.getParameter().get("parentDepartment");
			String departName = context.getParameter().get("name");
			if (departName != null) {
				long parentDepartment = Long.parseLong(parentDepartmentPara);
				Session se = HibernateUtil.getSessionFactory().openSession();
				DepartmentEntity de = (DepartmentEntity) se.get(DepartmentEntity.class, parentDepartment);
				if (de != null) {
					DepartmentEntity newDe = new DepartmentEntity();
					newDe.setName(departName);
					newDe.setParentDepartment(de);
					se.beginTransaction();
					se.save(newDe);
					se.getTransaction().commit();
					se.close();
					context.success();
				}

			}
		}

	}

}
